<template>
    <div v-show="userState.pageIndex === 0" class="login_container">
        <h3 v-show="userState.logintabNum === 0">邮箱登录</h3>
        <h3 v-show="userState.logintabNum === 1">手机验证码登录</h3>
        <div class="tabLogin">
            <button @click="tabLogin(0)" :class="{'active': userState.logintabNum === 0 }">密码登录</button>
            <button @click="tabLogin(1)" :class="{'active': userState.logintabNum === 1}">手机验证码登录</button>
        </div>
        <!-- 密码登录 -->
        <div v-show="userState.logintabNum===0" class="passLogin">
            <div class="input_row">
                <el-form class="el_form" :model="userData" :rules="rules" ref="formRef">
                    <el-form-item label="账号" prop="email">
                        <el-input 
                            type="text" 
                            auto-complete="off" 
                            v-model="userData.email" 
                            :placeholder="userState.betaVersion?'内测用户请输入邮箱':'请输入邮箱'"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input 
                            type="password" 
                            show-password 
                            v-model="userData.password"  
                            :placeholder="'请输入密码'"
                            ></el-input>
                    </el-form-item>
                    <el-form-item label="" prop="isread" class="centered_item">
                        <div class="read_row">
                            <el-checkbox name="isread" class="read_checkbox" v-model="userData.isread"/> 我已经阅读并同意
                            <a href="javascript:;" @click="userAgreement" >《用户协议》</a>和
                            <a href="javascript:;" @click="privacyPolicy">《隐私政策》</a>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <div class="to_pass_login">
                            <button type="button" class="login_btn" @click="submitForm">
                                登录
                            </button>
                        </div>
                        <!-- 第三方授权登录 -->
                        <div class="orther_login" >
                            <button type="button" @click="toWxLogin">第三方授权登录</button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>  
        </div>
        <!-- 验证码登录 -->
        <div v-show="userState.logintabNum===1" class="phoneLogin">
            <div class="input_row">
                <el-form class="el_form" :model="phoneData" :rules="phoneRules" ref="phoneFormRef">
                    <el-form-item label="" prop="phoneNumber">
                        <el-input 
                            type="text"
                            v-model="phoneData.phoneNumber"
                            :placeholder="userState.betaVersion?'内测用户请输入手机号码':'请输入手机号码'"
                            >
                            <!-- <template #prepend>
                                <el-select 
                                    class="input_select"
                                    :validate-event="false"
                                    v-model="phoneData.area" 
                                    :suffix-transition="false"
                                    placeholder="+86" 
                                    popper-class="el_select"
                                    :popper-append-to-body="false"
                                    >
                                    <el-option label="+86" value="+86" />
                                    <el-option label="+87" value="+87" />
                                    <el-option label="+88" value="+88" />
                                </el-select>
                            </template> -->
                        </el-input>
                    </el-form-item>
                    <el-form-item label="" prop="code">
                        <el-col :span="17">
                            <el-input 
                                type="text" 
                                v-model="phoneData.code"  
                                placeholder="请输入验证码"
                                ></el-input>
                        </el-col>
                        <el-col :span="7">
                            <div class="phoneCode_con">
                                <button type="button" :disabled="phoneCodeDisabled" @click="getPhoneCode">{{ getPhoneText }}</button>
                            </div>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="" prop="isread" class="centered_item">
                        <div class="read_row">
                            <el-checkbox name="isread" class="read_checkbox" v-model="phoneData.isread"/> 我已经阅读并同意
                            <a href="javascript:;" @click="userAgreement">《用户协议》</a>和
                            <a href="javascript:;" @click="privacyPolicy">《隐私政策》</a>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <div class="to_pass_login">
                            <button type="button" class="login_btn" @click="phoneSubmitForm">
                                登录
                            </button>
                        </div>
                        <!-- 第三方授权登录 -->
                        <div class="orther_login">
                            <button type="button" @click="toWxLogin">第三方授权登录</button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>  
        </div>
        <div class="regist_findpass">
            <!-- <p>没有账号？<router-link tag="a">立即注册</router-link></p> -->
            <p>没有账号？<a href="javascript:;" @click="toRegist">立即注册</a></p>
            <p>忘记密码？<router-link tag="a">找回密码</router-link></p>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, inject, toRaw, getCurrentInstance } from 'vue';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import { login, sendSmsForLogin, loginBySmsCode } from '../../api/login';
import { getUserInfo } from '../../api/user';
import { useUserStore } from '../../store/user';
import { useRoute } from 'vue-router'
const { userState,setUsername,setToken  } = useUserStore();

const formRef = ref(null);                  // 邮箱手机号form对象
const phoneFormRef = ref(null)              // 验证码登录form对象
// let userState.logintabNum = ref(0)                    // 切换密码登录与手机验证码登录 1.密码登录， 2.手机验证码登录
let phoneCodeDisabled = ref(false)          // 倒计时读秒时禁用获取验证码按钮
let getPhoneText = ref('获取验证码')          // 倒计时显示读秒
let second = 60                             // 倒计时秒数
let timer = null                            // 倒计时setInterval
let loginLoading  = null
const route = useRoute();

const instance = getCurrentInstance();
const eventBus = instance?.proxy.$eventBus;

let userData = reactive({
    email: '', //'24194481@qq.com',
    password: '', //'123123',
    isread: false
})
 // phoneData.phoneNumber
let phoneData = reactive({
    phoneNumber: '',
    code: '',
    isread: false
})

const isReadValidator = (rule, value, callback) => {
    if (!value) {
        return callback('请先勾选协议')
    } else {
        callback()
    }
}

// 《用户协议》
function userAgreement() {
    if (process.env.NODE_ENV === 'development') { // 测试
        ElMessageBox.confirm('<div>11111</div>',{
            confirmButtonText: '同意',
            showClose: false,
            showCancelButton: false,
            dangerouslyUseHTMLString: true,
            showCancelButton: false
        })
    }
}

// 《隐私政策》
function privacyPolicy() {

}

// 切换密码登录或者验证码登录
function tabLogin(index) {
    userState.logintabNum = index
}

// 订阅（接受）爷组件中的 provide 事件
// const checkLogin = inject('checkLogin')

// 邮箱/手机号登录
function submitForm() {
    formRef.value.validate((valid) => {
        if(valid) {
            loginLoading = ElLoading.service({
                target: document.querySelector('.login_container'),
                text: '登录中请稍后',
                customClass: 'custom-loading',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            login(toRaw(userData)).then(res => {
                console.log('res::::', res)
                if ( res.status === 200 ) {
                    loginMethod(res)
                }
            }).catch( error => {
                loginLoading.close()
            })
        }
    })
}

const rules = {
    email: [
        {required: true, message: '请输入邮箱', trigger: 'blur'},
    ],
    password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
    ],
    isread: [
        { validator: isReadValidator,  trigger: 'change'}
    ]
}

// 验证码登录校验
const phoneRules = {
    phoneNumber: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^[1][3-9][0-9]{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ],
    isread: [
        {validator: isReadValidator,trigger: 'change'}
    ]
}



// 获取验证码
function getPhoneCode() {
    phoneFormRef.value.validateField('phoneNumber', (valid) => {
        console.log(valid)
        // toLogin()
        if (valid) {
            phoneCodeDisabled.value = true
            second-- 
            getPhoneText.value = second+'秒后重新发送'
            timer = setInterval(() =>{
                second-- 
                getPhoneText.value = second+'秒后重新发送'
                if (second<=0) {
                    getPhoneText.value = '获取验证码'
                    second = 10
                    phoneCodeDisabled.value = false
                    clearInterval(timer)
                }
            },1000)

            sendSmsForLogin({
                phoneNumber: phoneData.phoneNumber
            }).then(res => {
                
            }).catch( error => {
                loginLoading.close()
            })

        }
    })
}



// 手机验证码登录
function phoneSubmitForm() {
    phoneFormRef.value.validate((valid) => {
        if (valid) {
            loginLoading = ElLoading.service({
                target: document.querySelector('.login_container'),
                text: '登录中请稍后',
                customClass: 'custom-loading',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            loginBySmsCode(phoneData).then(res => {
                if (res.status === 200) {
                    loginMethod(res)
                } else {
                    ElMessage({
                        message: '获取验证码失败',
                        type: 'error',
                        duration: 5 * 1000
                    })
                }
            })
        }
    })
}

// 统一登录方法
function loginMethod(res) {
    console.log('loginMethod-res:', res)
    const data = res.data.data
    if ( res.data.status ) {
        setToken(data.token)
        userState.id = data.id
        userState.isShowLogin = false 
        console.log('loginMethod:',userState)
        ElMessage({
            message: res.data.msg,
            type: 'success',
            duration: 5 * 1000
        })

        getUserInfo().then(res => {
            console.log('获取用户信息：', res)
            const userData = res.data.data
            if (res.status === 200) {
                userState.email = userData.email
                userState.username = userData.username
                userState.nickname = userData.nickname
                userState.tel = userData.tel
                userState.avatar = userData.avatar
                console.log('route.name:', route.name)
                if ( route.name.includes('AIMusic') ) {
                    location.reload()
                    userState.isShowLogin = false
                }
            }
        })
    } else {
        ElMessage({
            message: res.data.msg,
            type: 'error',
            duration: 5 * 1000
        })
    }
    loginLoading.close()
}


// 第三方授权登录
userState.wechatLogin = false
function toWxLogin() {
    userState.logintabNum = 0
    // resetUserData()
    // phoneFormRef.value.clearValidate()
    userState.pageIndex = 1
    userState.wechatLogin= true

}

// 立即注册
function toRegist() {
    
    userState.logintabNum = 0
    // resetUserData()
    // phoneFormRef.value.clearValidate()
    userState.pageIndex = 2
}

</script>

<style scoped>

.el-form-item {
    margin-bottom: 30px;
}

.el-input {
    --el-input-focus-border-color: #FFF !important;
}

.login_container h3 {
    font-size: 18px;
    font-weight: 400;
}

.tabLogin {
    width: 424px;
    height: 39px;
    border: 1px solid #FFF;
    border-radius: 5px;
    margin-top: 20px;
    padding: 2px;
    box-sizing: border-box;
    
}

.tabLogin button{
    border-radius: 6px;
    width: 209px;
    height: 33px;
    color: #FFF;
    transition: all .5s;
    cursor: pointer;
    font-size: 16px;
}

.tabLogin button.active {
    background: linear-gradient(90deg, rgba(82, 240, 227, 1) 0%, rgba(243, 114, 255, 1) 100%);
}


.passLogin, .phoneLogin {
    margin-top: 30px;
}

.input_row {
    width: 424px;
    display: flex;
    flex-direction: row;
    justify-content:flex-end;
    align-items: center;
    gap: 10px;
    padding-bottom: 24px;
    position: relative;
    margin-top: 10px;
}

.err_message {
    position: absolute;
    left: 100px;
    /* color: #d03050; */
    color: #f272ff;
    bottom: 0;
}

.input_row p span {
    /* color: #d03050; */
    color: #f272ff;
    margin-right: 2px;
}

.input_con {
    width: 324px;
    height: 34px;
    border-radius: 5px;
    border: 1px solid #FFF;
    display: flex;
    flex-direction: row;
}

.input_con input {
    width: 84%;
    height: 100%;
    border: none;
    padding-left: 10px;
    background: none;
    color: #FFF;
    font-size: 14px;
    /* border-right: 1px solid #FFF; */
}

::-webkit-input-placeholder {
    color: #ddd;
}


.centered_item {
    display: flex;
    flex-direction: row;
    justify-content: center; /* 水平居中 */
}

.read_row {
    width: 100% ;
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
    gap: 5px; /* 可调整间距 */
}

.read_row a {
    color: #7848f1;
}

.checkPass{
    width: 10%;
    cursor: pointer;
}

.checkPass img{
    width: 20px;
    height: 20px;
}

.to_pass_login {
    width: 420px;
    height: 40px;
    margin-top: 20px;
    position: relative;
}

.to_pass_login::before {
    content: '';
    width: 150px;
    height: 1px;
    background-color: #FFF;
    position: absolute;
    left: 0;
    top: 19px;
}

.to_pass_login::after {
    content: '';
    width: 150px;
    height: 1px;
    background-color: #FFF;
    position: absolute;
    right: 0;
    top: 19px;
}

.login_btn {
    width: 110px;
    height: 36px;
    background: linear-gradient(to bottom, rgba(82, 240, 227, 1) 0%, rgba(243, 114, 255, 1) 130%);
    border-radius: 5px;
    color: #FFF;
    font-size: 16px;
    display: block;
    margin: 0 auto;
    cursor: pointer;
    border: none;
}

.orther_login {
    width: 100%;
    margin-top: 10px;
}

.orther_login button {
    display: block;
    margin: 0 auto;
    color: #ccc0ed;
}

.el-checkbox:last-of-type {
    /* margin-right: 10px; */
}

.to_pass_login .el-button {
    color: #FFF;
}


.regist_findpass {
    width: 75%;
    height: 20px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    position: absolute;
    bottom: 50px;
}

.regist_findpass a {
    color: #7848f1
}

.centered_item ::v-deep(.el-form-item__error) {
    /* color: red; */
    /* color:#f272ff; */
    /* color: #53f0e3; */
    margin-left: 48px !important;
    margin-top: -8px !important;
}

.input_select {
    width: 70px;
    background: none !important;
    color: #FFF !important;
}

:deep(.el-input-group__prepend ) {
    background: none !important;
}

:deep(.el-select__wrapper) {
    background: none !important;
    border: none !important;
    box-shadow: none !important;
}

:deep(.el-input-group--prepend .el-input-group__prepend .el-select .el-select__wrapper){
    box-shadow: none !important;
    color: #FFF !important;
}

:deep(.el-select__placeholder.is-transparent) {
    color: #FFF !important;
}
:deep(.el-select__caret) {
    color: #FFF !important;
}

:deep(.el-select__placeholder) {
    color: #FFF !important;
}

:deep(.el-input__validateIcon) {
    display: none !important;
}

.el_select .el-select-dropdown__item.is-selected {
    color: #f373ff;
}


.phoneCode_con {
    padding-left: 10px;
}

.phoneCode_con button {
    width: 100%;
    height: 36px;
    border-radius: 5px;
    background-color: rgba(255,255,255,.5);
    color: #FFF;
    border:1px solid #FFF;
    box-sizing: border-box;
}


input:-webkit-autofill {
    background-color: transparent !important;
  color: #FFF !important;
  box-shadow: 0 0 0px 1000px transparent inset !important;
  -webkit-box-shadow: 0 0 0px 1000px transparent inset !important;
}

input:-internal-autofill-previewed,
input:-internal-autofill-selected {
    -webkit-text-fill-color: #FFF;
    transition: background-color 1000s ease-out 0.5s;
}

/* 进一步保证 autofill 输入框内部的文字和背景样式 */
input:-webkit-autofill::first-line {
  color: white !important;
  background-color: transparent !important;
}

/* 可选: 解决浏览器中 focus 时的样式干扰 */
input:focus:-webkit-autofill {
  background-color: transparent !important;
  color: white !important;
}


:deep(.el-input__wrapper) {
      height: 32px !important;
      background-color: transparent !important;
      border: none;
      box-shadow: 0 0 0 1px #FFF !important;
  }

:deep(.el-input__inner) {
  color: #FFF;
  font-size: 14px !important;
    box-shadow: 0 0 0 1000px transparent inset;
}

:deep(.el-form-item__label) {
    font-size: 14px !important;
    line-height: 36px  !important;
}



</style>

